<?php

namespace app\common\cachemodel;

use app\common\lib\exception\ApiException;
use app\common\model\BaseCache;
use think\Exception;
use XznsTools\cache\CacheManage;

class ZlcrAstrPush extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zlcr_astr_push';

    protected $cacheModel = 'astr_admin.push_regid';


    /**
     * 获取用户推送设备ID
     * @param int $astrId
     * @return array
     * @throws \Exception
     */
    public function getUserRegid(int $astrId): array
    {
        $userPushData = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $astrId)->getDataAndSet(function () use ($astrId)
        {
            try
            {
                $data = $this->where('astr_id', $astrId)->findOrFail()->toArray();
            }
            catch (Exception $e)
            {
                \think\Log::write('获取用户推送设备ID失败，ZyhsUserPush->getUserRegid()：' . $e->getMessage(), 'error');
                $data = [];
            }

            return $data ?: [''];
        });

        if (count($userPushData) < 2)
        {
            $userPushData = array_filter($userPushData);
        }
        return arrayKeyData2int($userPushData, ['id', 'astr_id', 'push_type', 'type', 'status', 'msg_status']);
    }

    public function Del(int $astrId)
    {
        try
        {
            $this->where(['astr_id' => $astrId])->delete();

            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $astrId)->rmCache();
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
        }
    }

    /**
     * 推送绑定
     * @param array $data
     * @param int $astrId
     * @throws ApiException
     * @throws \Exception
     */
    public function pushBindNew(array $data, int $astrId)
    {
        $userPushData = $this->getUserRegid($astrId);
        try
        {
            if ($userPushData)
            {
                $this->where('id', $userPushData['id'])->update($data);
                CacheManage::getInstance()->setCacheConfig($this->cacheModel, $astrId)->setCache($data);
            } else
            {
                $data['astr_id'] = $astrId;
                self::create($data);
                CacheManage::getInstance()->setCacheConfig($this->cacheModel, $astrId)->rmCache();
            }
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            throw new ApiException('推送绑定失败', 200, config('code.error'));
        }
    }
}